<?php

/**
*	找回密码
*
*/

//包含公共文件
include '../../common/common.php';

//接收post的传值
// var_dump($_POST);
$oldPwd   = trim($_POST['oldPwd']);
$newPwd = trim($_POST['newPwd']);
$rePwd    = trim($_POST['rePwd']);
$email     = trim($_POST['email']);
$question = trim($_POST['question']);
$answer   = trim($_POST['answer']);

//打印
// var_dump($oldPwd);
// var_dump($newPwd);	 
// var_dump($rePwd);	 	 
//var_dump($email);   
// var_dump($question);         
// var_dump($answer);

//查询用户当前的密码
$username = $_COOKIE['username'];
$resMsg =  mySelect($link , '*' , DB_TABLE_USER , "where username = '$username'");
$resPwd = $resMsg[0]['password'];
$resEmail = $resMsg[0]['email'];
//var_dump($resEmail);
//var_dump($resPwd);

//判断旧密码是否为空
if (!$oldPwd) {

	exit('旧密码不得为空<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
}
//判断旧的密码是否正确
if (md5($oldPwd) !== $resPwd) {

	exit('旧密码输入错误<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
}

//判断是否修改密码
if ($newPwd) {
	
	//判断新密码长度
	if (strlen($newPwd) < 3 || strlen($newPwd) > 12) {

		exit('密码长度只能在3~12位字符之间<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
	}
	//判断新密码是否为纯数字
	if (is_numeric($newPwd)) {

		exit('新密码不能为纯数字<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
	}
	//判断两次新密码是否一致
	if ($newPwd !== $rePwd) {

		exit('两次新密码输入不一致<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
	}
	$data['password'] = md5($newPwd); 
}

//判断是否输入邮箱
if ($email) {

	//判断邮箱格式是否正确
	$ePattern = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
	if (!preg_match($ePattern,$email)) {

		exit('邮箱格式错误<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
	}

	//判断是否与原邮箱相等
	if ($email != $resEmail) {

		$data['email'] = "$email";
	}

}

//判断提问的答案是否为空
if (!($question == '无安全提问' || $question == '保持原有的安全提问和答案')) {

	if (!$answer) {

		exit('请作出对应的回答<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
	}
	
}

//判断问题是否有回答
$data['question'] = $question;
$data['answer']   = $answer;

//判断提问是否需要更改
if ($question == '保持原有的安全提问和答案' || $question == '无安全提问') {
	//var_dump($data);
	unset($data['question']);
	unset($data['answer']);
}

//判断关联数组是否为空
if (!$data) {

	exit('没有要修改的内容<br /> <a href="'  . $_SERVER['HTTP_REFERER'] .'">返回上一页</a>');
}
//var_dump($data);

//修改数据库
$username = $_COOKIE['username'];
$resSafe = myUpdate($link , DB_TABLE_USER , $data , "username = '$username'");
//var_dump($resSafe);

//处理结果集
if ($resSafe && mysqli_affected_rows($link)) {

	echo '修改成功';
} else {

	echo '修改失败';
}

//跳转到上一页
header('refresh:1;url=' . $_SERVER['HTTP_REFERER']);